package com.hctforgreen.greenservice;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.model.EntryCatalogEntity;
import com.hctforgreen.greenservice.model.EntryCatalogEntity.EntryLevel1Entity;
import com.hctforgreen.greenservice.ui.adapter.EntryCatalogListAdapter;
import com.hctforgreen.greenservice.utils.EntryDetailUtil;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.KeyboardUtil;
import com.hctforgreen.greenservice.utils.Utils;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 资料目录展示页面(三级)
 *
 * @author Tallen Zhai
 */
public class EntryCatalogActivity extends ParentActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_entry_catalog);
        initSkinLayout();
        initTitleButtonBar();
        initWindow();

    }

    // private void initSkinLayout() {
    // FrameLayout parentLyt = (FrameLayout) findViewById(R.id.lyt_parent);
    // parentLyt.setBackgroundResource(ThemeStoreUtil.getSkinId(this));
    // }

    private void initTitleButtonBar() {
        String displayName = (String) getIntent().getSerializableExtra(
                HctConstants.ON_ACTIVITY_KEY_DISPLAY_NAME);
        String titleContents = getIntent().getStringExtra(
                HctConstants.ON_ACTIVITY_KEY_ENTRY_TITLE_CONTENTS);
        final TextView titleTv = (TextView) findViewById(R.id.tv_title);
        if (titleContents.equals("")) {
            titleTv.setText(displayName);
        } else if (!titleContents.equals("")) {
            titleTv.setText(titleContents);
        }

        final ImageButton backBtn = (ImageButton) findViewById(R.id.btn_back);
        backBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                KeyboardUtil keyboardUtil = new KeyboardUtil();
                keyboardUtil.hideSoftKeyboard(v);
                finish();
            }
        });

    }

    private boolean bUseCurrentId() {
        Intent intent = getIntent();
        String bookId = intent
                .getStringExtra(HctConstants.ON_ACTIVITY_KEY_BOOK_ID);

        if (bookId.equals("")) {
            return true;
        } else {
            return false;
        }
    }

    private void initWindow() {
        // String filePath =
        // getIntent().getStringExtra(HctConstants.ON_ZIP_SDCARD_PATH_KEY);
        String bookId = "";
        if (bUseCurrentId()) {
            bookId = (String) getIntent().getSerializableExtra(
                    HctConstants.ON_ACTIVITY_KEY_CURRENT_BOOK_ID);
        } else {
            bookId = (String) getIntent().getSerializableExtra(
                    HctConstants.ON_ACTIVITY_KEY_BOOK_ID);
        }

        String titleContents = getIntent().getStringExtra(
                HctConstants.ON_ACTIVITY_KEY_ENTRY_TITLE_CONTENTS);
        if (titleContents.equals("")) {
            loadEntryCatalogList(bookId, /* filePath, */"");
        } else if (!titleContents.equals("")) {
            loadEntryCatalogList(bookId, /* filePath, */titleContents);
        }
        initSearchBar(bookId);
        initRightButton(bookId);
    }

    private void initRightButton(final String bookId) {
        final Button btnRight = (Button) findViewById(R.id.btn_right);
        btnRight.setBackgroundResource(R.drawable.btn_advice_selector);
        btnRight.setVisibility(View.VISIBLE);
        btnRight.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(),
                        SubmitAdviceActivity.class);
                intent.putExtra(HctConstants.ON_ACTIVITY_KEY_BOOK_ID, bookId);
                startActivity(intent);
            }
        });
    }

    private void renderEntryCatalogList(View convertView, ListView listView,
                                        EntryCatalogEntity entity) {
        if (entity.dataList == null) {
            Toast.makeText(EntryCatalogActivity.this, R.string.is_not_complete_entry_catalog, Toast.LENGTH_SHORT).show();
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {

                @Override
                public void run() {
                    finish();
                }
            }, 500);
            return;
        }
        String machineName = getIntent().getStringExtra(
                HctConstants.ON_ACTIVITY_KEY_SEARCH_MACHINE_NAME);

        new EntryCatalogListAdapter(listView, EntryCatalogActivity.this,
                convertView, entity, entity.dataList, machineName,
                bUseCurrentId());
    }

    private void loadEntryCatalogList(final String bookId, final String titleContents) {
        final View convertView = findViewById(R.id.lyt_parent);
        final ListView listView = (ListView) convertView
                .findViewById(R.id.lst_default_list);
        final LinearLayout loadLyt = (LinearLayout) convertView
                .findViewById(R.id.lyt_default_list_load);
        final LinearLayout reloadLyt = (LinearLayout) convertView
                .findViewById(R.id.lyt_default_list_reload);
        final Button reloadBtn = (Button) convertView
                .findViewById(R.id.btn_default_list_reload);

        @SuppressLint("HandlerLeak") final Handler handler = new Handler() {
            public void handleMessage(Message msg) {

                HctResult hctResult = new HctResult();
                switch (msg.what) {
                    case HctConstants.STATUS_SUCCESS:
                        loadLyt.setVisibility(View.GONE);
                        reloadLyt.setVisibility(View.GONE);
                        listView.setVisibility(View.VISIBLE);
                        hctResult = (HctResult) msg.obj;
                        EntryCatalogEntity entity = (EntryCatalogEntity) hctResult.data;
                        if (entity.dataList != null && entity.dataList.size() == 1) {
                            DirectlyStartEntryDetailActivity(bookId, titleContents, entity);
                            return;
                        }
                        renderEntryCatalogList(convertView, listView, entity);
                        break;
                    case HctConstants.STATUS_FAILD:
                        loadLyt.setVisibility(View.GONE);
                        reloadLyt.setVisibility(View.VISIBLE);
                        listView.setVisibility(View.GONE);
                        reloadBtn.setOnClickListener(new OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                loadEntryCatalogList(bookId, /* filePath, */
                                        titleContents);
                            }
                        });
                        break;
                }
            }

            /**
             * 直接开启详情页
             *
             * @param bookId
             * @param titleContents
             * @param entity
             */
            private void DirectlyStartEntryDetailActivity(final String bookId,
                                                          final String titleContents, EntryCatalogEntity entity) {
                EntryLevel1Entity level1Entity = entity.dataList.get(0);

                String machineName = getIntent().getStringExtra(
                        HctConstants.ON_ACTIVITY_KEY_SEARCH_MACHINE_NAME);
                EntryDetailUtil detailUtil = new EntryDetailUtil();

                String displayName = (String) getIntent().getSerializableExtra(
                        HctConstants.ON_ACTIVITY_KEY_DISPLAY_NAME);

                detailUtil.startEntryDetailActivity(EntryCatalogActivity.this,
                        entity, bUseCurrentId(), machineName, level1Entity.id,
                        displayName, bookId, 1);

                finish();
            }

        };

        loadLyt.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 用此法屏蔽掉FrameLayout下面Layout的点击事件
            }
        });
        reloadLyt.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 用此法屏蔽掉FrameLayout下面Layout的点击事件
            }
        });
        loadLyt.setVisibility(View.VISIBLE);
        reloadLyt.setVisibility(View.GONE);
        new Thread() {
            public void run() {
                Message message = new Message();
                try {
                    HctController controller = new HctController(
                            EntryCatalogActivity.this);

                    HctResult result = controller.getEntryCatalogList(bookId,
                            titleContents);
                    if (result.status == HctConstants.STATUS_SUCCESS) {
                        message.what = result.status;
                        message.obj = result;
                    } else {
                        message.what = HctConstants.STATUS_FAILD;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                handler.sendMessage(message);
            }
        }.start();
    }

    // =====================
    // FIXME 1.5期 “模糊搜索”功能
    // =====================
    private void clearFocus() {

        /**
         * 使用EditText左侧的ImageView抢Focus
         */
        ImageView searchIconIv = (ImageView) findViewById(R.id.iv_search_icon);
        searchIconIv.requestFocus();

        final EditText searchInputEt = (EditText) findViewById(R.id.et_search_input);
        searchInputEt.clearFocus();
    }

    private void initSearchBar(final String bookId) {

        final EditText searchInputEt = (EditText) findViewById(R.id.et_search_input);
        final ImageButton clearBtn = (ImageButton) findViewById(R.id.btn_clear);
        searchInputEt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String sInput = searchInputEt.getText().toString().trim();
                if (sInput.equals("")) {
                    clearBtn.setVisibility(View.GONE);
                } else if (!sInput.equals("")) {
                    clearBtn.setVisibility(View.VISIBLE);
                }
            }
        });
        searchInputEt.setOnKeyListener(new OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_SEARCH
                        || keyCode == KeyEvent.KEYCODE_UNKNOWN
                        || keyCode == KeyEvent.KEYCODE_ENTER) {
                    String sSearchKey = searchInputEt.getEditableText()
                            .toString().trim();

                    if (!sSearchKey.equals("")) {
                        loadFuzzySearchEntryCatalogList(bookId, sSearchKey);
                    } else if (sSearchKey.equals("")) {
                        initWindow();
                    }
                    KeyboardUtil keyboardUtil = new KeyboardUtil();
                    keyboardUtil.hideSoftKeyboard(v);
                    clearFocus();
                    return true;
                }
                return false;
            }

        });
        clearBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                searchInputEt.setText("");
                initWindow();
            }
        });

    }

    private void loadFuzzySearchEntryCatalogList(final String bookId,
                                                 final String sSearchKey) {
        final View convertView = findViewById(R.id.lyt_parent);
        final ListView listView = (ListView) convertView
                .findViewById(R.id.lst_default_list);
        final LinearLayout loadLyt = (LinearLayout) convertView
                .findViewById(R.id.lyt_default_list_load);
        final LinearLayout reloadLyt = (LinearLayout) convertView
                .findViewById(R.id.lyt_default_list_reload);
        final Button reloadBtn = (Button) convertView
                .findViewById(R.id.btn_default_list_reload);

        final Handler handler = new Handler() {
            public void handleMessage(Message msg) {

                HctResult hctResult = new HctResult();
                switch (msg.what) {
                    case HctConstants.STATUS_SUCCESS:

                        Utils.submitPoints(EntryCatalogActivity.this, 1, "", false);

                        loadLyt.setVisibility(View.GONE);
                        reloadLyt.setVisibility(View.GONE);
                        listView.setVisibility(View.VISIBLE);

                        hctResult = (HctResult) msg.obj;

                        EntryCatalogEntity entity = (EntryCatalogEntity) hctResult.data;
                        if (entity.dataList == null) {
                            Toast.makeText(EntryCatalogActivity.this,
                                    R.string.fuzzy_search_entry_catalog_is_null,
                                    Toast.LENGTH_SHORT).show();
                            return;
                        }
                        renderEntryCatalogList(convertView, listView, entity/*
                                                                         * ,
																		 * "filePath"
																		 *//*
                                                                             * ,
																			 * "bookId"
																			 */);
                        break;

                    case HctConstants.STATUS_FAILD:
                        loadLyt.setVisibility(View.GONE);
                        reloadLyt.setVisibility(View.VISIBLE);
                        listView.setVisibility(View.GONE);
                        reloadBtn.setOnClickListener(new OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                loadEntryCatalogList(bookId, sSearchKey);
                            }
                        });
                        break;
                }
            }

        };

        loadLyt.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 用此法屏蔽掉FrameLayout下面Layout的点击事件
            }
        });
        reloadLyt.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 用此法屏蔽掉FrameLayout下面Layout的点击事件
            }
        });
        loadLyt.setVisibility(View.VISIBLE);
        reloadLyt.setVisibility(View.GONE);
        new Thread() {
            public void run() {
                Message message = new Message();
                try {
                    HctController controller = new HctController(
                            EntryCatalogActivity.this);

                    HctResult result = controller.fuzzySearchEntryCatalogList(
                            bookId, sSearchKey);
                    if (result.status == HctConstants.STATUS_SUCCESS) {
                        message.what = result.status;
                        message.obj = result;
                    } else {
                        message.what = HctConstants.STATUS_FAILD;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                handler.sendMessage(message);
            }
        }.start();
    }
}
